<template>
  <BasicModal width="800" @register="registerModal" destroyOnClose :title="getTitle"
    :showCancelBtn="true" :showOkBtn="true" :okText="isUpdate ? '保存' : '提交'" 
    :canFullscreen="false" :centered="true" :maskClosable="false" :scrollbar="{native: false}"
    @ok="handleSubmit" @cancel="handleCancel"
  >
    <BasicForm @register="registerForm" :model="modelRef">
      <!-- 自定义规格列表插槽 -->
      <template #skuList="{ model, field }">
        <div class="spec-list-container" style="margin-top: 20px;">
          <div v-for="(sku, index) in skuList" :key="index" class="spec-item" style="margin-bottom: 16px; padding: 16px; border: 1px solid #d9d9d9; border-radius: 6px;">
            <div style="display: flex; align-items: center; gap: 16px;">
              <!-- 规格项名称 -->
              <div style="flex: 1;">
                <label style="display: block; margin-bottom: 4px; font-weight: 500;">规格项名称</label>
                <a-input 
                  v-model:value="sku.name" 
                  placeholder="请输入规格项名称（如：颜色、尺寸等）"
                  style="width: 100%;"
                />
              </div>
              
              <!-- 规格值 -->
              <div style="flex: 2;">
                <label style="display: block; margin-bottom: 4px; font-weight: 500;">规格值</label>
                <a-input 
                  v-model:value="sku.spec_values" 
                  placeholder="请输入规格值，多个值用逗号分隔（如：红色,蓝色,绿色）"
                  style="width: 100%;"
                />
              </div>
              
              <!-- 删除按钮 -->
              <div style="flex: 0 0 auto; margin-top: 22px;">
                <a-button  type="link" 
                  danger 
                  @click="removeSpec(sku, index)"
                  :disabled="skuList.length <= 1"
                >
                  删除
                </a-button>
              </div>
            </div>
          </div>
          
          <!-- 新增规格按钮 -->
          <div style="text-align: center; margin-top: 16px;">
            <a-button type="dashed" @click="addSpec(model[field], model, field)" style="width: 100%;">
              新增规格
            </a-button>
          </div>
        </div>
      </template>
    </BasicForm>
    
  </BasicModal>
</template>

<script lang="ts" name="goodsOperation" setup>
import {ref, computed, unref, reactive, onMounted} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, useForm} from '/@/components/Form';
import {createGoods, editGoods} from '/@/views/shop/goods/goods-seller/goods.api';
import {useMessage} from "/@/hooks/web/useMessage";

const { createMessage: $message } = useMessage();

// 声明Emits
const emit = defineEmits(['success', 'register']);

//表单所有值，外部可更新
const modelRef  = ref<any>({});

// 是否正在上传
const isUploadingRef = ref(false);

const isUpdate = ref(true);

const skuList = ref([ { id: '', name: '', spec_values: '' } ]);

// 添加规格项
const addSpec = (specList, model, field) => {
  console.log(specList, model, field);
  if (skuList.value.length > 1) {
    // specList.push({
    //   name: '',
    //   spec_values: ''
    // });
  } else {
    // Object.assign(model, {
    //   skuList: [{
    //     name: '',
    //     spec_values: ''
    //   }]
    // });
    // model.skuList = [{
    //   name: '',
    //   spec_values: ''
    // }]
    skuList.value.push({
      id: '',
      name: '11',
      spec_values: '22'
    })
    //console.error('addSpec: specList is not an array');
  }
};

// 删除规格项
const removeSpec = (skuList, index) => {
  if (skuList.length > 1) {
    skuList.splice(index, 1);
  }
};

//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  //清空表间
  await resetFields();
  //设置表单值
  modelRef.value = {};

  setFieldsValue({
    //skuList: data.skuList || [{ name: '', spec_values: '' }]
  });
});

//表单配置
const [registerForm, {resetFields, setFieldsValue, updateSchema, validate}] = useForm({
  schemas: [
    { label: "", field: "id", component: "Input", show: false },
    { label: "商品名称", field: "goodsName", component: "Input", required: true, defaultValue: "商品名称" },
    { label: "商品金额", field: "price", component: "Input", required: true, defaultValue: "1000" },
    { label: "运费", field: "templateId", component: "Input", required: true, defaultValue: "0" },
    { label: "库存", field: "stock", component: "Input", required: true, defaultValue: "100" },
    { label: "商品类型", field: "goodsType", component: "Input", required: true, defaultValue: "TOUR_GOODS" },
    //{ label: "商品图片", field: "imgUrl", component: "Upload", required: true, defaultValue: "0" },
    { label: "商品描述", field: "goodsDesc", component: "InputTextArea", required: true, defaultValue: "0" },
    { label: "排序", field: "sort", component: "InputNumber", componentProps: { placeholder: " " } },
    { 
      label: "商品规格", 
      field: "skuList", 
      component: "Input", 
      colProps: {
        span: 24
      },
      slot: 'skuList'
    }
  ],
  labelWidth: 90,
  baseColProps: {span: 22},
  showActionButtonGroup: false,
});


// 标题
const getTitle = computed(() => {
  let text = '新增';

  // 标题
  text = (!unref(isUpdate) ? '新增' : ( isUploadingRef.value ? '查看' : '编辑' ));

  return text;
});

// 提交
async function handleSubmit() {
  try {
    setModalProps({confirmLoading: true});
    const values = await validate();

    values.skuList = skuList.value;

    // 过滤掉空白的规格项
    // if (values.skuList) {
    //   values.specList = values.specList.filter(spec => spec.name && spec.spec_values);
    // }
    
    await createGoods(values).then((res) => {
      if (res.success) {
        $message.success(res.message);
        //关闭弹窗
        closeModal();
        emit("success")
      } else {
        $message.warning(res.message);
      }
    });
  } catch (e) {
    console.log(e);
  } finally {
    setModalProps({confirmLoading: false});
  }
}

// 取消
function handleCancel () {
  closeModal()
}

onMounted(() => {
  
})
</script>

<style lang="less" scoped>
:deep(.ant-input-number .ant-input-number-input) {
  padding: 0 3px !important;
}
:deep(.ant-input-affix-wrapper) {
  padding: 0px !important;
}

// 规格列表样式
.spec-list-container {
  :deep(.ant-input) {
    border-radius: 4px;
  }
  
  :deep(.ant-btn-dashed) {
    border-style: dashed;
    border-color: #d9d9d9;
  }
  
  .spec-item {
    transition: all 0.3s;
    
    &:hover {
      border-color: #1890ff;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
    }
  }
}
</style>
